package com.authine.cloudpivot.ext.controller.workList;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Optional;


@Slf4j
@RestController
@RequestMapping("/public/LocalArchivesInfoController/")
public class LocalArchivesInfoController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    /**
     * 场地档案状态汇总表  审批流完成后 数据写到-场地档案状态汇总表基础表
     */
    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.ArchivesInfo, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.ArchivesInfoDetail);
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, "Activity3");
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                // 判断是否是修改
                String basicId = MapUtils.getString(map, "basicId", "");
                if (StringUtils.isNotBlank(basicId)) {
                    //基础信息表id
                    data.put("id", basicId);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.ArchivesInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);

                finishOrModifiyProcess(data);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * ------场地档案点检汇总
    *
     [SyncSiteArchCheck]
     @SiteCode		nvarchar(100),			-----场地代码
     @S01		NVARCHAR(10),				-----01 报告  'yes' then  '√'   'no' then '×'    '/'
     @S02        NVARCHAR(10),				---- 02 划分
     @S03        NVARCHAR(10),				---- 03 档案信息
     @S05        NVARCHAR(10),				---- 05 管理责任
     @S06        NVARCHAR(10),				---- 06 定置
     @S07        NVARCHAR(10),				---- 07 疏散图
     @S08        NVARCHAR(10),				---- 08 电路图
     @S09        NVARCHAR(10),				---- 09 张贴信息
     @S10		NVARCHAR(10),				-----10 卫生周期   2024.03.07增
     @S12		NVARCHAR(10),				-----12 让步记录   2024.03.07增
     @S14        NVARCHAR(10),				---- 14 专项档案
     @Auth       NVARCHAR(10),				---- 授权
     @Desc		nvarchar(200),				------说明
     @Auditor	nvarchar(100)				------02.0100 张三
     */
    private void finishOrModifiyProcess(Map<String, Object> map) {
        if (map == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        String siteCodeString = (String) map.get("siteCodeString");
        String report = zhuanhuan(MapUtils.getString(map, "report", ""));
        String division = zhuanhuan(MapUtils.getString(map, "division", ""));
        String archivesInfo = zhuanhuan(MapUtils.getString(map, "archivesInfo", ""));
        String responsibility = zhuanhuan(MapUtils.getString(map, "responsibility", ""));
        String location = zhuanhuan(MapUtils.getString(map, "location", ""));
        String evacuate = zhuanhuan(MapUtils.getString(map, "evacuate", ""));
        String electric = zhuanhuan(MapUtils.getString(map, "electric", ""));
        String infomation = zhuanhuan(MapUtils.getString(map, "infomation", ""));


        String healthCycle = zhuanhuan(MapUtils.getString(map, "healthCycle", ""));
        String issueConcession = zhuanhuan(MapUtils.getString(map, "issueConcession", ""));


        String archives = zhuanhuan(MapUtils.getString(map, "archives", ""));
        String auth = zhuanhuan(MapUtils.getString(map, "auth", ""));
        String workContent = MapUtils.getString(map, "workContent", "");
        String approval = MapUtils.getString(map, "approval", ""); // 审批人
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncSiteArchCheck '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                siteCodeString, report, division, archivesInfo, responsibility,
                location, evacuate, electric, infomation,healthCycle,issueConcession, archives,
                auth, workContent, approval);
        log.info("\n==========准备调用[场地档案落实汇总表]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[场地档案落实汇总表]存储过程执行完成");
    }

    private String zhuanhuan(String value){
        switch (value) {
            case "√":
                value = "yes";
                break;
            case "×":
                value = "no";
                break;
            case "/":
                value = "/";
                break;
        }
        return value;
    }


    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.ArchivesInfoCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.ArchivesInfoDetailCancel);
        //获取审批人
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, "Activity3");
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                String basicId = MapUtils.getString(map, "basicId", "");
                if (StringUtils.isNotBlank(basicId)) {
                    //基础信息表id
                    data.put("id", basicId);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.ArchivesInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                Map<String, Object> company = (Map<String, Object>) map.get("company");

                //存储过程未提供
//                toVoidProcess(company.get("id").toString(),MapUtils.getString(map, "eventCode", ""));
            } catch (Exception e) {
                log.info("参数：{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * 场地档案落实汇总表作废存储过程
     */
    private void toVoidProcess(String companyNumber, String eventCode) {
        String execSql = String.format("exec [HG_LINK].[hg].[dbo]. '%s'",
                companyNumber, eventCode);
        log.info("\n==========准备调用[场地档案落实汇总表]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[场地档案落实汇总表]存储过程执行完成");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String finalActivityCode) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }
}
